package src

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"gitee.com/haifengat/goctp"
	ctp "gitee.com/haifengat/goctp/lnx"
	"github.com/sirupsen/logrus"
)

func startTrade() {
	logrus.Infoln("connected to trade...")

	var chConnected = make(chan bool)
	t.RegOnFrontConnected(func() {
		logrus.Infoln("trade connected")
		chConnected <- true
		go t.ReqLogin(investorID, password, brokerID, appID, authCode)
	})
	t.RegOnFrontDisConnected(func(reason int) {
		logrus.Info("trade disconnected ", reason)
		if reason != 0 {
			releaseTrade()
		}
	})
	t.RegOnRspUserLogin(onLogin)
	t.ReqConnect(tradeFront)
	go func() {
		// 连接超时设置
		select {
		case <-chConnected:
		case <-time.After(10 * time.Second):
			fmt.Println("连接超时")
			releaseTrade()
		}
	}()
}
func releaseTrade() {
	t.Release()
	t = ctp.NewTrade()
}

func onLogin(login *goctp.RspUserLoginField, info *goctp.RspInfoField) {
	logrus.Infof("trade login info: %v", info)
	if info.ErrorID == 7 { // 未初始化
		go func() {
			time.Sleep(1 * time.Minute) // 一分钟试一次
			t.ReqLogin(investorID, password, brokerID, appID, authCode)
		}()
	} else if info.ErrorID != 0 {
		go releaseTrade()
	} else {
		actionDay = "" // 初始化
		instLastMin = sync.Map{}
		// minPushed = sync.Map{}
		// mapInstrumentStatus = sync.Map{} // 会导致收不到行情：登录事件时交易状态已更新
		// 初始化 actionday
		if t, err := time.Parse("20060102", login.TradingDay); err == nil {
			preDay, _ := rdb.HGet(ctx, "tradingday", "curday").Result()
			if strings.Compare(preDay, login.TradingDay) != 0 {
				logrus.Info("清仓数据: ", preDay)
				rdb.FlushAll(ctx)
				execTicks = 0
				rdb.HSet(ctx, "tradingday", "curday", login.TradingDay)
			}
			if t.Weekday() == time.Monday { // 周一
				actionDay = t.AddDate(0, 0, -3).Format("20060102")     // 上周五
				actionDayNext = t.AddDate(0, 0, -2).Format("20060102") // 上周六
			} else {
				actionDay = t.AddDate(0, 0, -1).Format("20060102") // 上一天
				actionDayNext = login.TradingDay                   // 本日
			}

			startQuote()
		} else {
			logrus.Error("日期字段错误：", login.TradingDay)
		}
	}
}
